#include "main.h"

int copy (FILE* fileToRead,FILE * fileToWrite, unsigned long long int fileSize, unsigned int * ChkSum)
{
int rc = 0;
char * buf = (char *) calloc (SIZE_BUF,sizeof(char));
if (!buf)	cl_exit (COPY,MEMORY_ERR);

	for (;;)	{
		if ((fileSize/(SIZE_BUF)) != 0)	{ 
			if ((rc = fread (buf,sizeof(char),SIZE_BUF,fileToRead)) != SIZE_BUF)	{
				free (buf);
				return -1;
			}
			if (fileToWrite) {
				strWrite (fileToWrite,buf,SIZE_BUF,ChkSum);
			}
			else {
				ChkSum[0] += Crc32 (buf,SIZE_BUF);
			}
			fileSize -= SIZE_BUF;
		}
		else { 
			if (fileSize > 0) { 
				if ((rc = fread (buf,sizeof(char),fileSize,fileToRead)) != fileSize)	{
					free (buf);
					return -1;
				}
					if (fileToWrite) {
						strWrite (fileToWrite,buf,fileSize,ChkSum);
					}
					else {
						ChkSum[0] += Crc32 (buf,fileSize);
					}	
					break;
			} else {
				break;
			}
		}
	}
	free (buf);
	return 0;
}